# vim: ft=ruby

fastlane_require "dotenv"
Dotenv.load("../.env")

fastlane_version "1.89.0"

default_platform :ios

platform :ios do
  desc "Runs all the tests"
  lane :test do
    run_tests(scheme: "Tropos")
  end

  desc "Submit a new Beta Build to Apple TestFlight"
  desc "This will also make sure the profile is up to date"
  lane :beta do |options|
    setup_certs

    next_build_number(options) do
      build
      testflight(skip_waiting_for_build_processing: true)
    end
  end

  desc "Deploy a new version to the App Store"
  lane :release do |options|
    setup_certs

    next_build_number(options) do
      build
      deliver(force: true)
    end
  end

  desc "Bump the version, tag and push"
  lane :bump_version do |options|
    next_build_number(options)
  end

  private_lane :build do
    build_ios_app(scheme: "Tropos", buildlog_path: "log")
  end

  private_lane :setup_certs do
    validate_env!
    match(type: "appstore", app_identifier: [
      "com.thoughtbot.carlweathers",
      "com.thoughtbot.carlweathers.TroposIntents",
    ])
  end
end

def next_build_number(options={})
  type = options.fetch(:type, "build")

  case type
  when "build"
    increment_build_number
  else
    increment_version_number(bump_type: type)
    increment_build_number
  end

  result = yield if block_given?

  commit_version_bump(xcodeproj: "Tropos.xcodeproj", ignore: %r{^(?!Sources)/})
  version = get_version_number(target: "Tropos")
  build = get_build_number
  add_git_tag(tag: "v#{version}+#{build}")
  push_to_git_remote

  result
end

def validate_env!
  username = ensure_deliver_username
  match_url = ensure_match_url
  if !username || !match_url
    offer_to_write_env_file
  end
end

def ensure_deliver_username
  username = ENV["DELIVER_USERNAME"]
  if !username || username.empty?
    ENV["DELIVER_USERNAME"] = UI.input("Please provide your Apple ID username:")
    ensure_deliver_username
  end
  username
end

def ensure_match_url
  match_url = ENV["MATCH_GIT_URL"]
  if !match_url || match_url.empty?
    ENV["MATCH_GIT_URL"] = UI.input("Please provide the URL to your match repo:")
    ensure_match_url
  end
  match_url
end

def offer_to_write_env_file
  return unless UI.interactive?

  if UI.confirm("Some environment variables were missing. "\
      "Would you like to write them to a .env file?")
    File.open("../.env", "w") do |file|
      file.puts("DELIVER_USERNAME=#{ENV["DELIVER_USERNAME"]}")
      file.puts("MATCH_GIT_URL=#{ENV["MATCH_GIT_URL"]}")
    end
  end
end
